package com.huawei.app.demo.fragment;

import java.util.concurrent.TimeUnit;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;

import com.huawei.app.demo.MainActivity;
import com.huawei.app.demo.MsgHandler;
import com.huawei.app.demo.R;
import com.huawei.app.demo.util.LogUtils;
import com.huawei.app.demo.video.HDMISurfaceCallback;
import com.huawei.app.httpapi.HttpApiResult;
import com.huawei.app.httpapi.IdeaHubHttpApiUtils;
import com.huawei.app.httpapi.ThreadPools;

/**
 * 投屏
 *
 * @since 2021-02-19
 */
public class CastFragment extends CustomFragment {

    private static final String TAG = CastFragment.class.getSimpleName();
    private Context context;
    private View rootView;
    private CheckBox toogleAirCodeDisplay;

    @Override
    public String getTitle() {
        return "投屏";
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (this.rootView != null) {
            return rootView;
        }
        this.context = getContext();
        this.rootView = inflater.inflate(R.layout.fragment_cast, container, false);

        // init view
        Button openCastPage = rootView.findViewById(R.id.openCastPage);
        this.toogleAirCodeDisplay = rootView.findViewById(R.id.toogleAirCodeDisplay);
        Button showInTopRight = rootView.findViewById(R.id.showInTopRight);
        Button showInBottomRight = rootView.findViewById(R.id.showInBottomRight);

        // init event
        openCastPage.setOnClickListener(this);
        this.toogleAirCodeDisplay.setOnClickListener(this);
        showInTopRight.setOnClickListener(this);
        showInBottomRight.setOnClickListener(this);

        return rootView;
    }

    /**
     * 初始化组件状态(例如Checkbox选中状态)
     */
    @Override
    public void initViewStatus() {
        int delayTime = 500;
        if (IdeaHubHttpApiUtils.getInstance().isLoginSuccess()) {
            delayTime = 0;
        }

        ThreadPools.schedule(new Runnable() {
            @Override
            public void run() {
                if (!IdeaHubHttpApiUtils.getInstance().isLoginSuccess()) {
                    return;
                }
                boolean checked = false;

                // 查询当前投屏码显示隐藏状态, 0表示隐藏, 1表示显示
                HttpApiResult apiResult = IdeaHubHttpApiUtils.getInstance().getParamValues(new String[]{"airCodeDisplay"});
                if ("0".equals(apiResult.getData().getString("airCodeDisplay"))) {
                    checked = true;
                }

                // 同步Checkbox勾选状态, 不触发单击事件
                Message msg = Message.obtain();
                msg.what = MsgHandler.UPDATE_VIEW_CHECK_STATUS;
                msg.obj = new MsgHandler.UpdateViewCheckStatus(R.id.toogleAirCodeDisplay, checked, false);
                if (msgHandler != null) {
                    msgHandler.sendMessage(msg);
                }
            }
        }, delayTime, TimeUnit.MILLISECONDS);
    }

    @Override
    public void onResume() {
        super.onResume();
        initViewStatus();
    }

    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        switch (viewId) {
            case R.id.openCastPage: {
                openCastPage();
                break;
            }
            case R.id.toogleAirCodeDisplay: {
                toogleAirCodeDisplay();
                break;
            }
            case R.id.showInTopRight: {
                showInTopRight();
                break;
            }
            case R.id.showInBottomRight: {
                showInBottomRight();
                break;
            }
            default: {
                break;
            }
        }
    }

    /**
     * 打开投屏引导页
     */
    public void openCastPage() {
        LogUtils.getInstance().i(TAG, "openCastPage begin.");

        Intent intent = new Intent("com.device.action.THIRDAPP_START_ACTIVITY");
        intent.putExtra("activityName", "Project");
        context.sendBroadcast(intent, "com.device.permission.THIRDAPP");

        LogUtils.getInstance().i(TAG, "openCastPage end.");
    }

    /**
     * 显示/隐藏WiFi图标, 投屏码
     */
    public void toogleAirCodeDisplay() {
        final boolean isHide = this.toogleAirCodeDisplay.isChecked();
        LogUtils.getInstance().i(TAG, "toogleAirCodeDisplay begin, isHide=" + isHide);

        ThreadPools.run(new Runnable(){
            @Override
            public void run() {
                try {
                    if (isHide) {
                        IdeaHubHttpApiUtils.getInstance().hideIcon();
                    } else {
                        IdeaHubHttpApiUtils.getInstance().showIcon();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        LogUtils.getInstance().i(TAG, "toogleAirCodeDisplay end, isHide=" + isHide);
    }

    /**
     * 投屏内容显示到右上角
     */
    public void showInTopRight() {
        if (context instanceof MainActivity) {
            ((MainActivity)context).showInTopRight();
        }
    }

    /**
     * 投屏内容显示到右下角
     */
    public void showInBottomRight() {
        LogUtils.getInstance().i(TAG, "showInBottomRight begin.");
        LinearLayout topRightPanel = getActivity().findViewById(R.id.topRightPanel);
        if (topRightPanel.getChildCount() > 0) {
            topRightPanel.removeAllViews();
        }

        LinearLayout bottomRightPanel = getActivity().findViewById(R.id.bottomRightPanel);
        if (bottomRightPanel.getChildCount() > 0) {
            bottomRightPanel.removeAllViews();
            bottomRightPanel.setVisibility(View.GONE);
            return;
        }
        if (!bottomRightPanel.isShown()) {
            bottomRightPanel.setVisibility(View.VISIBLE);
        }

        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.cast_surface, null);
        SurfaceView castSurfaceview = view.findViewById(R.id.castSurfaceview);
        castSurfaceview.getHolder().addCallback(new HDMISurfaceCallback(castSurfaceview));

        bottomRightPanel.addView(view);
        LogUtils.getInstance().i(TAG, "showInBottomRight end.");
    }
}
